<?php


namespace App\Services;

use App\Models\IdentityCard;
use Illuminate\Support\Facades\Log;

/**
 * 身份证验证服务
*/
class IdentifyService
{
    /** 实名认证功能 (阿里云,云市场服务商)
     * @param $realName 真实姓名
     * @param $idCard 身份证号码
     */
    public function verify2($realName='',$idCard=''){
        //先判断数据库中是否有这个身份证
        $exists = IdentityCard::query()->where('name',$realName)->where('id_card',$idCard)->exists();
        if ($exists) return true;
        $host = "https://smrzhy.market.alicloudapi.com";
        $path = "/smrz/dmp/api/jinrun.idcard.verify.idcard";
        $method = "POST";
        $appcode = "1a018cbdca69425b823af5cd6fd60d44";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        // 根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
        $jsonStr = '{"name":"'.$realName.'","idcard":"'.$idCard.'"}';
        $bodys = "biz_content=" . urlencode($jsonStr);
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);

        $result = curl_exec($curl);

        // varmp($result); // {"request_id":"SN1720341422546227200","code":"1","data":{"data":{"resultMsg":"认证成功","result":"1"},"seqNum":"3623110300522761","message":"成功","status":0},"message":"认证成功","timestamp":1698996332906}"
        $result = json_decode($result,true);
        $code = $result['code'] ?? null;
        if ($code==1){
            IdentityCard::query()->insert([
                'name'=>$realName,
                'id_card'=>$idCard
            ]);
            return true;
        } else {
            Log::info("identify false ! realName: $realName idCard: $idCard code: $code");
            return false;
        }
    }

}
